<template>
  <div class="file-uploader">
    <el-upload
      class="uploader"
      drag
      action="#"
      multiple
      :accept="acceptFormats"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :auto-upload="false"
      ref="uploadRef"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        点击或拖拽文件至此处上传
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持格式：CSV/TSV/XLSX/FASTQ；单个文件最大100MB；单次最多上传5个文件
        </div>
      </template>
    </el-upload>
    <div class="upload-controls" v-if="fileList.length > 0">
       <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">
        上传到服务器
      </el-button>
      <el-button size="small" type="danger" @click="clearFiles">清空列表</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';

const emit = defineEmits(['upload-success']);

const uploadRef = ref(null);
const fileList = ref([]);
const acceptFormats = '.csv,.tsv,.xlsx,.fastq';
const maxFileSize = 100; // MB
const maxFileCount = 5;

const beforeUpload = (rawFile) => {
  const fileType = rawFile.name.split('.').pop().toLowerCase();
  const isAcceptedFormat = ['csv', 'tsv', 'xlsx', 'fastq'].includes(fileType);
  if (!isAcceptedFormat) {
    ElMessage.error(`文件格式不支持: ${rawFile.name}`);
    return false;
  }

  const isLtMaxSize = rawFile.size / 1024 / 1024 < maxFileSize;
  if (!isLtMaxSize) {
    ElMessage.error(`文件大小超过 ${maxFileSize}MB: ${rawFile.name}`);
    return false;
  }
  
  return true;
};

const handleChange = (file, files) => {
  // 在这里可以处理文件状态变化，例如显示进度
   fileList.value = files;
};

const handleRemove = (file, files) => {
  fileList.value = files;
};

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `当前限制选择 ${maxFileCount} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
      files.length + uploadFiles.length
    } 个文件`
  );
};

const submitUpload = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件');
    return;
  }
  
  // 模拟上传
  ElMessage.info('开始上传...');
  let successCount = 0;
  const successfulFiles = [];
  
  fileList.value.forEach((file, index) => {
    setTimeout(() => {
      // 模拟成功或失败
      if (Math.random() > 0.2) {
        file.status = 'success';
        successCount++;
        successfulFiles.push(file.raw || file); // 保存成功上传的文件
        ElMessage.success(`${file.name} 上传成功`);
      } else {
        file.status = 'fail';
        ElMessage.error(`${file.name} 上传失败`);
      }
      
      // 所有文件处理完毕
      if (index === fileList.value.length - 1) {
        ElMessage.info(`上传完成，${successCount}个成功，${fileList.value.length - successCount}个失败。`);
        if(successCount > 0) {
            // 传递成功上传的文件列表给父组件
            emit('upload-success', successfulFiles);
        }
        clearFiles();
      }
    }, 1000 * (index + 1)); // 模拟网络延迟
  });
};

const clearFiles = () => {
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
    fileList.value = [];
  }
};
</script>

<style scoped>
.file-uploader {
  text-align: center;
}
.uploader .el-upload__tip {
  margin-top: 10px;
  color: #909399;
}
.upload-controls {
  margin-top: 20px;
}
</style>
